//
//  SJLoginViewController.m
//  WSL
//
//  Created by CJ on 2017/9/26.
//  Copyright © 2017年 sanjuetech. All rights reserved.
//

#import "SJLoginViewController.h"
#import "SJLoginApi.h"
#import "SJFindPw1ViewController.h"

@interface SJLoginViewController ()

@property (nonatomic, strong) UIScrollView *containView;
@property (nonatomic, strong) UITextField *phoneField;
@property (nonatomic, strong) UIView *phoneBG;
@property (nonatomic, strong) UITextField *verifyField;
@property (nonatomic, strong) UIView *verifyBG;
@property (nonatomic, strong) UIButton *registerButton;

@property (nonatomic, strong) UIView *navigationBarView;

@end

@implementation SJLoginViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [SJStatisticTool beginLogPageView:NSStringFromClass([self class])];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [SJStatisticTool endLogPageView:NSStringFromClass([self class])];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setupUI];
}

- (void)setupUI {
    
    [self.view addSubview:self.navigationBarView];
    
    if (812 == SJScreenH) {
        self.navigationBarView.sd_layout
        .leftSpaceToView(self.view, SJLayoutFrame(0))
        .topSpaceToView(self.view, SJLayoutFrame(40))
        .heightIs(SJLayoutFrame(50))
        .widthIs(SJScreenW);
    } else {
        self.navigationBarView.sd_layout
        .leftSpaceToView(self.view, SJLayoutFrame(0))
        .topSpaceToView(self.view, SJLayoutFrame(0))
        .heightIs(SJLayoutFrame(50))
        .widthIs(SJScreenW);
    }
    
    [self.view addSubview:self.containView];
    self.containView.sd_layout
    .leftSpaceToView(self.view, SJLayoutFrame(0))
    .topSpaceToView(self.navigationBarView, SJLayoutFrame(0))
    .rightSpaceToView(self.view, SJLayoutFrame(0))
    .bottomSpaceToView(self.view, SJLayoutFrame(0));
    
    [self.containView addSubview:self.phoneBG];
    self.phoneBG.sd_layout
    .centerXEqualToView(self.containView)
    .topSpaceToView(self.containView, SJLayoutFrame(75))
    .widthIs(SJLayoutFrame(295))
    .heightIs(SJLayoutFrame(43));
    
    [self.containView addSubview:self.verifyBG];
    self.verifyBG.sd_layout
    .centerXEqualToView(self.containView)
    .topSpaceToView(self.phoneBG, SJLayoutFrame(30))
    .widthIs(SJLayoutFrame(295))
    .heightIs(SJLayoutFrame(43));
    
    [self.containView addSubview:self.registerButton];
    self.registerButton.sd_layout
    .centerXEqualToView(self.containView)
    .topSpaceToView(self.verifyBG, SJLayoutFrame(73))
    .widthIs(SJLayoutFrame(295))
    .heightIs(SJLayoutFrame(43));
    
    UIButton *lostButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [lostButton setImage:[UIImage imageNamed:@"login_lostpassword"] forState:UIControlStateNormal];
    [lostButton addTarget:self action:@selector(lostPassword) forControlEvents:UIControlEventTouchUpInside];

    [self.containView addSubview:lostButton];
    lostButton.sd_layout
    .rightSpaceToView(self.containView, SJLayoutFrame(55))
    .topSpaceToView(self.verifyBG, SJLayoutFrame(10))
    .widthIs(SJLayoutFrame(47))
    .heightIs(SJLayoutFrame(11.5));
    
    // scrollview自动contentsize
    //    [self.containView setupAutoContentSizeWithBottomView:self.otherLoginView bottomMargin:0];
    
}

- (void)lostPassword {
    
    SJFindPw1ViewController *findPwVC = [SJFindPw1ViewController new];
    [self.navigationController pushViewController:findPwVC animated:YES];
    
}


#pragma mark - gerter


- (UIView *)navigationBarView{
    
    if (!_navigationBarView) {
        
        _navigationBarView = [UIView new];
        _navigationBarView.backgroundColor = [UIColor clearColor];
        
        
        // 返回
        UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [backButton setImage:[UIImage imageNamed:@"addtext-icon-return"] forState:UIControlStateNormal];
        [backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
        
        [_navigationBarView addSubview:backButton];
        backButton.sd_layout
        .centerYEqualToView(_navigationBarView)
        .leftSpaceToView(_navigationBarView, SJLayoutFrame(10))
        .heightIs(SJLayoutFrame(30))
        .widthIs(SJLayoutFrame(30));
        
        // 词条输入
        UILabel *wordLabel = [UILabel new];
        wordLabel.textColor = SJColorHexString(@"#ffffff");
        wordLabel.font = [UIFont fontWithName:@"Helvetica" size:SJLayoutFrame(17)];
        wordLabel.textAlignment = NSTextAlignmentCenter;
        wordLabel.text = @"密码登录";
        
        [_navigationBarView addSubview:wordLabel];
        wordLabel.sd_layout
        .centerYEqualToView(_navigationBarView)
        .centerXEqualToView(_navigationBarView)
        .heightIs(SJLayoutFrame(27));
        [wordLabel setSingleLineAutoResizeWithMaxWidth:SJScreenW * .5];
        
    }
    return _navigationBarView;
}

- (void)backAction {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (UIView *)phoneBG {
    
    if (!_phoneBG) {
        
        _phoneBG = [UIView new];
        _phoneBG.sd_cornerRadius = @(SJCornerRadius);
        _phoneBG.backgroundColor = SJColorHexString(@"#ffffff19");
        _phoneBG.layer.borderColor = [UIColor clearColor].CGColor;//边框颜色
        _phoneBG.layer.borderWidth = SJLayoutFrame(1);//边框宽度
        
        UIImageView *leftImage = [UIImageView new];
        leftImage.image = [UIImage imageNamed:@"personal_icon_phone"];
        
        [_phoneBG addSubview:leftImage];
        leftImage.sd_layout
        .centerYEqualToView(_phoneBG)
        .leftSpaceToView(_phoneBG, SJLayoutFrame(10))
        .widthIs(SJLayoutFrame(25))
        .heightIs(SJLayoutFrame(25));
        
        [_phoneBG addSubview:self.phoneField];
        self.phoneField.sd_layout
        .leftSpaceToView(leftImage, SJLayoutFrame(15))
        .topSpaceToView(_phoneBG, SJLayoutFrame(0))
        .rightSpaceToView(_phoneBG, SJLayoutFrame(0))
        .bottomSpaceToView(_phoneBG, SJLayoutFrame(0));
        
    }
    return _phoneBG;
}

- (UIView *)verifyBG {
    
    if (!_verifyBG) {
        
        _verifyBG = [UIView new];
        _verifyBG.sd_cornerRadius = @(SJCornerRadius);
        _verifyBG.backgroundColor = SJColorHexString(@"#ffffff19");
        _verifyBG.layer.borderColor = [UIColor clearColor].CGColor;//边框颜色
        _verifyBG.layer.borderWidth = SJLayoutFrame(1);//边框宽度
        
        UIImageView *leftImage = [UIImageView new];
        leftImage.image = [UIImage imageNamed:@"personal_setpassword_password"];
        
        [_verifyBG addSubview:leftImage];
        leftImage.sd_layout
        .centerYEqualToView(_verifyBG)
        .leftSpaceToView(_verifyBG, SJLayoutFrame(10))
        .widthIs(SJLayoutFrame(25))
        .heightIs(SJLayoutFrame(25));
        
        
        [_verifyBG addSubview:self.verifyField];
        self.verifyField.sd_layout
        .leftSpaceToView(leftImage, SJLayoutFrame(15))
        .topSpaceToView(_verifyBG, SJLayoutFrame(0))
        .rightSpaceToView(_verifyBG, SJLayoutFrame(0))
        .bottomSpaceToView(_verifyBG, SJLayoutFrame(0));
        
    }
    return _verifyBG;
}

- (BOOL)isValidateMobile:(NSString *)mobile {
    
    NSPredicate* phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"1[345678]([0-9]){9}"];
    
    return [phoneTest evaluateWithObject:mobile];
    
}

- (UIButton *)registerButton{
    
    if (!_registerButton) {
        
        _registerButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_registerButton addTarget:self action:@selector(registerAction) forControlEvents:UIControlEventTouchUpInside];
        [_registerButton setImage:[UIImage imageNamed:@"login_loginsicang"] forState:UIControlStateNormal];
        
    }
    return _registerButton;
}

- (void)registerAction {
    
    if (![self.phoneField.text isNotBlank] || ![self.verifyField.text isNotBlank]) {
        
        NSString *msg = @"请输入手机号或密码";
        [SVProgressHUD showErrorWithStatus:msg];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    // 1.拼接参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"phone"] = self.phoneField.text;
    parameters[@"pwd"] = [self.verifyField.text md5String];
    parameters[@"type"] = @"2";
    
    SJLoginApi *api = [[SJLoginApi alloc] initWithParameters:parameters];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            
            [SJUserDefaults setObject:api.responseObject[@"content"][@"token"] forKey:SJToken];
            [SJUserDefaults setObject:api.responseObject[@"content"] forKey:SJUserInfo];
            [SJUserDefaults synchronize];
            
            [self dismissViewControllerAnimated:YES completion:nil];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:SJDidLoginNotification object:nil];
            });
        } else {
            
            NSString *msg = api.responseObject[@"result"][@"msg"];
            [SVProgressHUD showErrorWithStatus:msg];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
        }
        
        
        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
        attributes[@"type"] = @"pwd";
        [SJStatisticTool event:@"login_pwd" attributes:attributes];
        
    } failure:^(YTKBaseRequest *request) {
        
    }];
    
}

- (UITextField *)phoneField{
    
    if (!_phoneField) {
        
        _phoneField = [UITextField new];
        _phoneField.returnKeyType = UIReturnKeyNext;
        _phoneField.keyboardType = UIKeyboardTypePhonePad;
        _phoneField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _phoneField.textColor = SJColorHexString(@"#ffffff");
        _phoneField.font = [UIFont systemFontOfSize:SJLayoutFrame(15)];
        
        // 编辑
        [_phoneField addTarget:self action:@selector(editingDidBegin:) forControlEvents:UIControlEventEditingDidBegin];
        [_phoneField addTarget:self action:@selector(editingDidEnd:) forControlEvents:UIControlEventEditingDidEnd];
        
        NSString *holderText = @"输入手机号";
        NSMutableAttributedString *placeholder = [[NSMutableAttributedString alloc]initWithString:holderText];
        [placeholder addAttribute:NSForegroundColorAttributeName
                            value:SJColorHexString(@"#ffffff90")
                            range:NSMakeRange(0, holderText.length)];
        [placeholder addAttribute:NSFontAttributeName
                            value:[UIFont systemFontOfSize:SJLayoutFrame(15)]
                            range:NSMakeRange(0, holderText.length)];
        _phoneField.attributedPlaceholder = placeholder;
        
    }
    return _phoneField;
}

- (void)editingDidBegin:(UITextField *)textField {
    
    if (textField == self.phoneField) {
        _phoneBG.layer.borderColor = [UIColor whiteColor].CGColor;//边框颜色
        
    } else {
        _verifyBG.layer.borderColor = [UIColor whiteColor].CGColor;//边框颜色
    }
}

- (void)editingDidEnd:(UITextField *)textField {
    
    if (textField == self.phoneField) {
        _phoneBG.layer.borderColor = [UIColor clearColor].CGColor;//边框颜色
        
    } else {
        _verifyBG.layer.borderColor = [UIColor clearColor].CGColor;//边框颜色
    }
}

- (UITextField *)verifyField{
    
    if (!_verifyField) {
        
        _verifyField = [UITextField new];
        _verifyField.returnKeyType = UIReturnKeyNext;
        _verifyField.keyboardType = UIKeyboardTypeDefault;
        _verifyField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _verifyField.textColor = SJColorHexString(@"#ffffff");
        _verifyField.font = [UIFont systemFontOfSize:SJLayoutFrame(15)];
        _verifyField.secureTextEntry = YES;
        _verifyField.enablesReturnKeyAutomatically = YES;
        
        // 编辑
        [_verifyField addTarget:self action:@selector(editingDidBegin:) forControlEvents:UIControlEventEditingDidBegin];
        [_verifyField addTarget:self action:@selector(editingDidEnd:) forControlEvents:UIControlEventEditingDidEnd];
        
        NSString *holderText = @"输入密码";
        NSMutableAttributedString *placeholder = [[NSMutableAttributedString alloc]initWithString:holderText];
        [placeholder addAttribute:NSForegroundColorAttributeName
                            value:SJColorHexString(@"#ffffff90")
                            range:NSMakeRange(0, holderText.length)];
        [placeholder addAttribute:NSFontAttributeName
                            value:[UIFont systemFontOfSize:SJLayoutFrame(15)]
                            range:NSMakeRange(0, holderText.length)];
        _verifyField.attributedPlaceholder = placeholder;
        
    }
    return _verifyField;
}

- (UIScrollView *)containView {
    
    if (!_containView) {
        
        _containView = [UIScrollView new];
        
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapAction)];
        singleTap.cancelsTouchesInView = NO;
        [_containView addGestureRecognizer:singleTap];
        
    }
    return _containView;
}

- (void)singleTapAction {
    
    [self.view endEditing:YES];
}

@end

